from flask import Blueprint, flash, render_template, request, redirect, url_for, session
from exts import db
from models import Statementmodel, Addstatementformmodel, Merchantmodel, Usermodel
from decorators import login_required
from sqlalchemy import and_

bp = Blueprint("sm", __name__, url_prefix="/sm")


@bp.route("/insert", methods=['GET', 'POST'])
@login_required
def insert():
    user_id = session['userid']
    user = Usermodel.query.filter_by(id=user_id).first()
    add_statement_form = Addstatementformmodel()
    merchants = Merchantmodel.query.all()
    statements = Statementmodel.query.filter_by(status='已保存')
    submitted_statements = Statementmodel.query.filter_by(status='待监管部门审核')
    if user.role == 'submitter':
        # 1.调用WTF的函数实现验证
        if add_statement_form.validate_on_submit():
            # 2.验证通过获取数据
            new_merchant_id = add_statement_form.merchant_id.data[0]
            new_since = add_statement_form.since.data
            new_till = add_statement_form.till.data
            new_zhenyuan_amount = add_statement_form.zhenyuan_amount.data
            new_wechat_amount = add_statement_form.wechat_amount.data
            new_service_fee = add_statement_form.service_fee.data
            new_statement_amount = add_statement_form.statement_amount.data
        # 3.判断同一商户下结算起止时间是否存在交叠, 如果有重叠就提示错误
        # if :
        # flash('该商户在这个时段内已有结算')
        # 4.没有重复就添加数据
            try:
                new_statement = Statementmodel(merchant_id=new_merchant_id,
                                           since=new_since,
                                           till=new_till,
                                           zhenyuan_amount=new_zhenyuan_amount,
                                           wechat_amount=new_wechat_amount,
                                           service_fee=new_service_fee,
                                           statement_amount=new_statement_amount,
                                           status='已保存'
                                           )
                db.session.add(new_statement)
                db.session.commit()
                flash('添加结付单成功')
                return redirect(url_for("sm.insert"))
            except Exception as e:
                print(e)
                flash('添加结付单失败')
                db.session.rollback()
        else:
            # 6. 验证不通过就提示错误
            if request.method == 'POST':
                print(add_statement_form.data)
                flash('参数不全')
        return render_template("add_statement.html", merchants=merchants, statements=statements,
                           submitted_statements=submitted_statements,
                           form=add_statement_form)
    else:
        return redirect(url_for("sm.process"))


# 删除结付单 --> 网页中删除-->点击需要发送结付单的ID给删除的路由 --> 路由需要接受参数
@bp.route("/delete/<statement_id>", methods=['GET', 'POST'])
@login_required
def delete(statement_id):
    # 1. 查询数据库, 是否有该ID的结付单, 如果有就删除, 没有提示错误
    statement = Statementmodel.query.get(statement_id)

    # 2. 如果有就删除
    if statement:
        try:
            db.session.delete(statement)
            db.session.commit()
            flash('删除结付单成功')
        except Exception as e:
            flash('删除结付单出错')
            db.session.rollback()

    else:
        # 3. 没有提示错误
        flash('找不到这张结付单')
    return redirect(url_for("sm.insert"))


# 提交结付单 --> 网页中提交-->点击需要发送结付单的ID给提交的路由 --> 路由需要接受参数
@bp.route("/submit/<statement_id>", methods=['GET', 'POST'])
@login_required
def submit(statement_id):
    # 1. 查询数据库, 是否有该ID的结付单, 如果有就提交 没有提示错误
    statement = Statementmodel.query.get(statement_id)
    user_id = session['userid']
    user = Usermodel.query.filter_by(id=user_id).first()
    username = user.username
    # 2. 如果有就提交
    if statement:
        try:
            statement.status = '待监管部门审核'
            statement.submitter = username
            db.session.commit()
            flash('提交结付单成功')
        except Exception as e:
            flash('提交结付单出错')
            db.session.rollback()

    else:
        # 3. 没有就提示错误
        flash('找不到这张结付单')
    return redirect(url_for("sm.insert"))


@bp.route("/process", methods=['GET', 'POST'])
@login_required
def process():
    user_id = session['userid']
    user = Usermodel.query.filter_by(id=user_id).first()
    if user.role == 'supervisor':
        statements = Statementmodel.query.filter_by(status='待监管部门审核')
        return render_template("process.html", statements=statements)
    elif user.role == 'examiner':
        statements = Statementmodel.query.filter_by(status='待财务部门初审')
        return render_template("process.html", statements=statements)
    elif user.role == 'assentor':
        statements = Statementmodel.query.filter_by(status='待财务部门同意')
        return render_template("process.html", statements=statements)
    elif user.role == 'approver':
        statements = Statementmodel.query.filter_by(status='待分管财务校长同意')
        return render_template("process.html", statements=statements)
    else:
        return redirect(url_for("sm.insert"))


@bp.route("/ratify/<statement_id>", methods=['GET', 'POST'])
@login_required
def ratify(statement_id):
    user_id = session['userid']
    user = Usermodel.query.filter_by(id=user_id).first()
    username = user.username
    # 1. 查询数据库, 是否有该ID的结付单, 如果有就提交 没有提示错误
    statement = Statementmodel.query.get(statement_id)
    if user.role == 'supervisor':
        statements = Statementmodel.query.filter_by(status='待监管部门审核')
        if statements:
            try:
                statement.status = '待财务部门初审'
                statement.supervisor = username
                db.session.commit()
                flash('处理结付单成功')
            except Exception as e:
                flash('处理结付单出错')
                db.session.rollback()
        else:
            # 3. 没有就提示错误
            flash('找不到这张结付单')
    elif user.role == 'examiner':
        statements = Statementmodel.query.filter_by(status='待财务部门初审')
        if statements:
            try:
                statement.status = '待财务部门同意'
                statement.examiner = username
                db.session.commit()
                flash('处理结付单成功')
            except Exception as e:
                flash('处理结付单出错')
                db.session.rollback()
        else:
            # 3. 没有就提示错误
            flash('找不到这张结付单')
    elif user.role == 'assentor':
        statements = Statementmodel.query.filter_by(status='待财务部门同意')
        if statements:
            if statement.statement_amount >= 300000.00:
                try:
                    statement.status = '待分管财务校长同意'
                    statement.assentor = username
                    db.session.commit()
                    flash('处理结付单成功')
                except Exception as e:
                    flash('处理结付单出错')
                    db.session.rollback()
            else:
                try:
                    statement.status = '待支付'
                    statement.assentor = username
                    db.session.commit()
                    flash('处理结付单成功')
                except Exception as e:
                    flash('处理结付单出错')
                    db.session.rollback()
        else:
            # 3. 没有就提示错误
            flash('找不到这张结付单')
    elif user.role == 'approver':
        statements = Statementmodel.query.filter_by(status='待分管财务校长同意')
        if statements:
            try:
                statement.status = '待支付'
                statement.approver = username
                db.session.commit()
                flash('处理结付单成功')
            except Exception as e:
                flash('处理结付单出错')
                db.session.rollback()

    else:
        # 3. 没有就提示错误
        flash('找不到这张结付单')
    return redirect(url_for("sm.process"))


@bp.route("/refuse/<statement_id>", methods=['GET', 'POST'])
@login_required
def refuse(statement_id):
    user_id = session['userid']
    user = Usermodel.query.filter_by(id=user_id).first()
    username = user.username
    # 1. 查询数据库, 是否有该ID的结付单, 如果有就提交 没有提示错误
    statement = Statementmodel.query.get(statement_id)
    if user.role == 'supervisor':
        statements = Statementmodel.query.filter_by(status='待监管部门审核')
        if statements:
            try:
                statement.status = '已保存'
                statement.supervisor = username
                db.session.commit()
                flash('处理结付单成功')
            except Exception as e:
                flash('处理结付单出错')
                db.session.rollback()
        else:
            # 3. 没有就提示错误
            flash('找不到这张结付单')
    elif user.role == 'examiner':
        statements = Statementmodel.query.filter_by(status='待财务部门初审')
        if statements:
            try:
                statement.status = '待监管部门审核'
                statement.examiner = username
                db.session.commit()
                flash('处理结付单成功')
            except Exception as e:
                flash('处理结付单出错')
                db.session.rollback()
        else:
            # 3. 没有就提示错误
            flash('找不到这张结付单')
    elif user.role == 'assentor':
        statements = Statementmodel.query.filter_by(status='待财务部门同意')
        if statements:
            try:
                statement.status = '待财务部门初审'
                statement.examiner = username
                db.session.commit()
                flash('处理结付单成功')
            except Exception as e:
                flash('处理结付单出错')
                db.session.rollback()
        else:
            # 3. 没有就提示错误
            flash('找不到这张结付单')
    elif user.role == 'approver':
        statements = Statementmodel.query.filter_by(status='待分管财务校长同意')
        if statements:
            try:
                statement.status = '待财务部门同意'
                statement.approver = username
                db.session.commit()
                flash('处理结付单成功')
            except Exception as e:
                flash('处理结付单出错')
                db.session.rollback()

    else:
        # 3. 没有就提示错误
        flash('找不到这张结付单')
    return redirect(url_for("sm.process"))


@bp.route("/payment", methods=['GET', 'POST'])
@login_required
def payment():
    user_id = session['userid']
    user = Usermodel.query.filter_by(id=user_id).first()
    statements = Statementmodel.query.filter_by(status='待支付')
    if user.role == 'submitter':
        return render_template("payment.html", statements=statements)
    else:
        return redirect(url_for("sm.insert"))


@bp.route("/pay/<statement_id>", methods=['GET', 'POST'])
@login_required
def pay(statement_id):
    # 1. 查询数据库, 是否有该ID的结付单, 如果有就提交 没有提示错误
    statement = Statementmodel.query.get(statement_id)
    user_id = session['userid']
    user = Usermodel.query.filter_by(id=user_id).first()
    # 2. 如果有就提交
    if user.role == 'submitter':
        statements = Statementmodel.query.filter_by(status='待支付')
        if statements:
            try:
                statement.status = '已完成'
                db.session.commit()
                flash('处理结付单成功')
            except Exception as e:
                flash('处理结付单出错')
                db.session.rollback()
        else:
            # 3. 没有就提示错误
            flash('找不到这张结付单')
        return redirect(url_for("sm.payment"))
    else:
        return redirect(url_for("sm.process"))
    return render_template("payment.html", statements=statements)


@bp.route("/emergency/<statement_id>", methods=['GET', 'POST'])
@login_required
def emergency(statement_id):
    # 1. 查询数据库, 是否有该ID的结付单, 如果有就提交 没有提示错误
    statement = Statementmodel.query.get(statement_id)
    statements = Statementmodel.query.filter_by(status='待支付')
    user_id = session['userid']
    user = Usermodel.query.filter_by(id=user_id).first()
    username = user.username
    # 2. 如果有就提交
    if statements:
        try:
            statement.status = '待财务部门初审'
            statement.submitter = username
            db.session.commit()
            flash('紧急止付成功，请与财务初审人员联系')
        except Exception as e:
            flash('紧急止付失败，是不是结付单已经打印了？')
            db.session.rollback()

    else:
        # 3. 没有就提示错误
        flash('找不到这张结付单')
    return redirect(url_for("sm.payment"))


@bp.route("/query", methods=['GET', 'POST'])
@login_required
def query():
    statements = Statementmodel.query.all()
    return render_template("query.html", statements=statements)
